package com.tongyi.lizhishop.activitys;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.transition.ChangeBounds;
import android.transition.ChangeImageTransform;
import android.transition.TransitionSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.tongyi.lizhishop.R;
import com.tongyi.lizhishop.api.StoreApi;
import com.tongyi.lizhishop.beans.CommonResonseBean;
import com.tongyi.lizhishop.beans.StoreBean;
import com.tongyi.lizhishop.common.BaseActivity;
import com.tongyi.lizhishop.common.CommonObserver;
import com.tongyi.lizhishop.common.MatisseUtils;
import com.tongyi.lizhishop.managers.APIServiceManager;
import com.tongyi.lizhishop.utils.PromptDialogUtils;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zhihu.matisse.Matisse;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.leefeng.promptlibrary.PromptDialog;

import static com.tongyi.lizhishop.activitys.StoreManagerActivity.getRealPathFromURI;

public class ViewPagerImageActivity extends BaseActivity implements RationaleListener {

    private static final int REQUEST_CODE_CHOOSE = 2;
    @BindView(R.id.uploadImage)
    ImageView uploadImage;
    @BindView(R.id.activity_view_pager_image)
    ScrollView activityViewPagerImage;
    @BindView(R.id.viewpageImageContaider)
    LinearLayout viewpageImageContaider;
    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    private List<Uri> images = new ArrayList<Uri>();
    private List<String> imagesStr = new ArrayList<String>();
    private PromptDialog prompDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager_image);
        ButterKnife.bind(this);
        initTitleBarView(titlebar, "轮播图");
        initView();
        prompDialog = PromptDialogUtils.getPrompDialog(this);
        loadData();
    }

    private void loadData() {
        prompDialog.showLoading("请等待");
        APIServiceManager.getInstance().create(StoreApi.class)
                .infoSeller(SPUtils.getInstance().getString("userid"))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CommonObserver<StoreBean>() {
                    @Override
                    public void onSuccess(StoreBean value) {
                        prompDialog.dismissImmediately();
                        if ("succ".equals(value.getRe())) {

                            imagesStr.addAll(value.getArray().getImages());

                            for (int i = 0; i < imagesStr.size(); i++) {
                                addImageToParent(imagesStr.get(i));
                            }
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        prompDialog.dismissImmediately();
                        ToastUtils.showShort("请求数据失败!请检查网络");

                    }
                });
    }

    private void initView() {
        for (Uri uri : images) {
            addImageToParent(uri);
        }
    }

    // 成功回调的方法，用注解即可，这里的300就是请求时的requestCode。
    @PermissionYes(100)
    private void getPermissionYes(List<String> grantedPermissions) {
        selectPicFromLocal();
    }

    @PermissionNo(100)
    private void getPermissionNo(List<String> deniedPermissions) {
        ToastUtils.showShort("请给予程序读取存储卡权限应用才能读取图片哦!");

    }

    @OnClick({R.id.uploadImage, R.id.saveBtn})
    public void onViewClicked(View view) {

        if (view.getId() == R.id.uploadImage) {
            // 在Activity：
            AndPermission.with(this)
                    .requestCode(100)
                    .permission(Permission.STORAGE)
                    .rationale(this)
                    .callback(this)
                    .start();
        } else if (view.getId() == R.id.saveBtn) {

            submitData1();
        }


    }

    public static final int VALUE_PICK_PICTURE = 2;

    private void selectPicFromLocal() {

        int maxSelectable = 7 - viewpageImageContaider.getChildCount();
        if (maxSelectable > 0) {
            MatisseUtils.pickImage(this, maxSelectable, REQUEST_CODE_CHOOSE);
        } else {
            ToastUtils.showShort("您最多可选择5张照片");
        }
    }


    List<Uri> mSelected;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainResult(data);
            Log.d("Matisse", "mSelected: " + mSelected);

            for (final Uri uri : mSelected) {
                images.add(uri);
                addImageToParent(uri);
            }
        }
    }

    private void addImageToParent(final String imageUrl) {
        final ImageView imageView = new ImageView(this);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onImageViewClicked(imageUrl, imageView);
            }
        });
        imageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                AlertDialog.newBuilder(ViewPagerImageActivity.this)
                        .setTitle("提示")
                        .setMessage("是否删除这张照片").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ((ViewGroup) imageView.getParent()).removeView(imageView);
                        imagesStr.remove(imageUrl);
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
                return true;
            }
        });
        imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(200)));
        viewpageImageContaider.addView(imageView, viewpageImageContaider.getChildCount() - 2);
        Glide.with(this).load(APIServiceManager.server_address + imageUrl).centerCrop().into(imageView);
    }


    private void addImageToParent(final Uri uri) {
        final ImageView imageView = new ImageView(this);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onImageViewClicked(uri, imageView);
            }
        });
        imageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                AlertDialog.newBuilder(ViewPagerImageActivity.this)
                        .setTitle("提示")
                        .setMessage("是否删除这张照片").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ((ViewGroup) imageView.getParent()).removeView(imageView);
                        images.remove(uri);
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
                return true;
            }
        });
        imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(200)));
        viewpageImageContaider.addView(imageView, viewpageImageContaider.getChildCount() - 2);
        Glide.with(this).load(uri).centerCrop().into(imageView);
    }

    private void onImageViewClicked(Object uri, ImageView imageView) {
        Bundle bundle = new Bundle();
        if (uri instanceof Uri) {
            bundle.putParcelable("uri", (Parcelable) uri);

        } else {
            bundle.putString("imageUrl", uri.toString());
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            TransitionSet mtransitionset = new TransitionSet();//制定过度动画set
            mtransitionset.addTransition(new ChangeBounds());//改变表框大小
            mtransitionset.addTransition(new ChangeImageTransform());//图片移动，还可以是其他的，要什么效果自己添加
            mtransitionset.setDuration(250);
            getWindow().setEnterTransition(mtransitionset);//注意，下面是必须的
            getWindow().setExitTransition(mtransitionset);
            getWindow().setSharedElementEnterTransition(mtransitionset);
            getWindow().setSharedElementExitTransition(mtransitionset);
            ActivityOptionsCompat aop = ActivityOptionsCompat.makeSceneTransitionAnimation(this,
                    imageView, "shareImageView");
            //指定imageView为共享元素，注意“123”,必须和SecondActivity**中共享的元素名称一致**，此处共享的元素可以是多个，多个元素，查看makeSceneTransitionAnimation的重载方法
            Intent intent = new Intent(getApplicationContext(), PhotoViewActivity.class);
            intent.putExtras(bundle);
            ActivityCompat.startActivity(this, intent, aop.toBundle());
        } else {
            ActivityUtils.startActivity(bundle, ViewPagerImageActivity.this, PhotoViewActivity.class);

        }
    }


    @Override
    public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
        AlertDialog.newBuilder(this)
                .setTitle("提示")
                .setMessage("选择图片需要给程序读取内存的权限").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                rationale.resume();
                dialog.dismiss();
            }
        });

    }

    /**
     * 上传轮播图
     */
    private void submitData1() {
        if (images.size() == 0 && imagesStr.size() == 0) {
            ToastUtils.showShort("请先选择图片");
            return;
        }
        prompDialog.showLoading("请等待");
        PostRequest<String> params = OkGo.<String>post(APIServiceManager.server_address + "/frontend.php/SelSeller/saveImages")
                .params("selid", SPUtils.getInstance().getString("userid"));
        ArrayList<File> files = new ArrayList<>(images.size());
        for (int i = 0; i < images.size(); i++) {
            Uri uri = images.get(i);
            String path = uri.getPath();
            LogUtils.w("path:" + path);
            String realPathFromURI = getRealPathFromURI(this, uri);
            files.add(new File(realPathFromURI));
        }
        params.addFileParams("image", files);
        params.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Gson gson = new Gson();
                CommonResonseBean commonResonseBean = gson.fromJson(response.body().toString(), CommonResonseBean.class);
                LogUtils.w(response.body());
                if ("succ".equals(commonResonseBean.getRe())) {
                    prompDialog.showSuccess("提交成功", false);
                    Intent data = new Intent();
                    data.putExtra("status", 1);
                    setResult(RESULT_OK, data);
                    finish();
                } else {
                    prompDialog.showError("提交失败,请重试", false);
                }

            }


        });

    }
}

